package cn.piesat.client.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 任务执行线程池控制工具类
 */
public class ThreadPoolLock {

    public AtomicInteger runSize = new AtomicInteger(0);

    private int maxSize = 10;

    private static final Object LOCK_OBJECT = new Object();

    /**
     * 构造函数，初始化线程池数量
     */
    public ThreadPoolLock(String taskThreadPoolSize){
        try {
            if(StringUtils.isNotBlank(taskThreadPoolSize)){
                int size = Integer.parseInt(taskThreadPoolSize);
                if(size>0){
                    maxSize = size;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 记录
     */
    public void record() {
        this.runSize.incrementAndGet();
    }

    /**
     * 放回
     */
    public void toEnd(){
        this.runSize.decrementAndGet();
    }

    /**
     * 等待
     */
    public void doWait() {
        synchronized (LOCK_OBJECT) {
            while (runSize.intValue() >= maxSize) {
                try {
                    LOCK_OBJECT.wait(1);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    LOCK_OBJECT.notifyAll();
                }
            }
        }
    }
}
